/**
 * Software License, Version 1.0
 * 
 * Copyright 2003 The Trustees of Indiana University. All rights reserved.
 * 
 * 
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 * 
 * 1) All redistributions of source code must retain the above copyright notice,
 * the list of authors in the original source code, this list of conditions and
 * the disclaimer listed in this license; 2) All redistributions in binary form
 * must reproduce the above copyright notice, this list of conditions and the
 * disclaimer listed in this license in the documentation and/or other materials
 * provided with the distribution; 3) Any documentation included with all
 * redistributions must include the following acknowledgement:
 * 
 * "This product includes software developed by the Community Grids Lab. For
 * further information contact the Community Grids Lab at
 * http://communitygrids.iu.edu/."
 * 
 * Alternatively, this acknowledgement may appear in the software itself, and
 * wherever such third-party acknowledgments normally appear.
 * 
 * 4) The name Indiana University or Community Grids Lab or NaradaBrokering,
 * shall not be used to endorse or promote products derived from this software
 * without prior written permission from Indiana University. For written
 * permission, please contact the Advanced Research and Technology Institute
 * ("ARTI") at 351 West 10th Street, Indianapolis, Indiana 46202. 5) Products
 * derived from this software may not be called NaradaBrokering, nor may Indiana
 * University or Community Grids Lab or NaradaBrokering appear in their name,
 * without prior written permission of ARTI.
 * 
 * 
 * Indiana University provides no reassurances that the source code provided
 * does not infringe the patent or any other intellectual property rights of any
 * other entity. Indiana University disclaims any liability to any recipient for
 * claims brought by any other entity based on infringement of intellectual
 * property rights or otherwise.
 * 
 * LICENSEE UNDERSTANDS THAT SOFTWARE IS PROVIDED "AS IS" FOR WHICH NO
 * WARRANTIES AS TO CAPABILITIES OR ACCURACY ARE MADE. INDIANA UNIVERSITY GIVES
 * NO WARRANTIES AND MAKES NO REPRESENTATION THAT SOFTWARE IS FREE OF
 * INFRINGEMENT OF THIRD PARTY PATENT, COPYRIGHT, OR OTHER PROPRIETARY RIGHTS.
 * INDIANA UNIVERSITY MAKES NO WARRANTIES THAT SOFTWARE IS FREE FROM "BUGS",
 * "VIRUSES", "TROJAN HORSES", "TRAP DOORS", "WORMS", OR OTHER HARMFUL CODE.
 * LICENSEE ASSUMES THE ENTIRE RISK AS TO THE PERFORMANCE OF SOFTWARE AND/OR
 * ASSOCIATED MATERIALS, AND TO THE PERFORMANCE AND VALIDITY OF INFORMATION
 * GENERATED USING SOFTWARE.
 */
package cgl.narada.samples.nbNative;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.Properties;

import cgl.narada.event.EventProperties;
import cgl.narada.event.NBEvent;
import cgl.narada.event.NBEventException;
import cgl.narada.event.TemplateProfileAndSynopsisTypes;
import cgl.narada.matching.Profile;
import cgl.narada.service.ServiceException;
import cgl.narada.service.client.ClientService;
import cgl.narada.service.client.EventConsumer;
import cgl.narada.service.client.EventProducer;
import cgl.narada.service.client.NBEventListener;
import cgl.narada.service.client.SessionService;

/**
 * A simple native client of NaradaBrokering. The SimpleClient example program
 * has been modified slightly to test the new IPSec tunneling capabilities.
 * 
 * @author Shrideep Pallickara
 * @author Craig Shue
 * $Date$ $Revision$
 */

public class SimpleIPSecClient implements NBEventListener {
    private int entityId;

    private ClientService clientService;

    private String moduleName = "SimpleClient: ";

    private EventConsumer consumer;

    private EventProducer producer;

    private Profile profile;

    private boolean addEventProperty = false;

    private String topic = "Movie/Casablanca";

    private ClientTransmissionTracker clientTransmissionTracker;

    private int tracker = 0;

    public SimpleIPSecClient(int entityId) {
        try {
            this.entityId = entityId;
            // SessionService.setServiceConfigurationLocation("D:/NaradaSources/config/ServiceConfiguration.txt");
            clientService = SessionService.getClientService(entityId);
            clientTransmissionTracker = new ClientTransmissionTracker(
                                                                      clientService);
        } catch (ServiceException serEx) {
            System.out.println(serEx);
        }

    }

    private void startClientTransmissionTracker() {
        clientTransmissionTracker.start();
    }

    private void stopClientTransmissionTracker() {
        clientTransmissionTracker.stopLooping();
    }

    public void initializeBrokerCommunications(Properties props, String commType)
        throws ServiceException {
        clientService.initializeBrokerCommunications(props, commType);
    }

    /**
     * Closes the connection to the broker.
     * 
     * @throws ServiceException
     */
    public void closeBrokerConnection() throws ServiceException {
        unsubscribe();
        clientService.closeBrokerConnection();
        clientService.terminateServices();
        stopClientTransmissionTracker();
        try {
            /** Make sure that the transmission tracker is shutdown gracefully. */
            Thread.sleep(100);
        } catch (InterruptedException e) {
            System.out.println(moduleName
                + "Problems sleeping while waiting for transfer completion");
        }
    }

    public void initializeProducer() throws ServiceException {
        producer = clientService.createEventProducer();

        producer.generateEventIdentifier(true);
        producer.setTemplateId(12345);
        producer.setDisableTimestamp(false);

        producer.setSuppressRedistributionToSource(true);
    }

    public void initializeConsumer() throws ServiceException {
        profile = clientService
            .createProfile(TemplateProfileAndSynopsisTypes.STRING, topic);
        consumer = clientService.createEventConsumer(this);
        consumer.subscribeTo(profile);
    }

    public void unsubscribe() throws ServiceException {
        consumer.unSubscribe(profile);
    }

    public void addEventProperty() {
        addEventProperty = true;
    }

    public void removeEventProperty() {
        addEventProperty = true;
    }

    public void publishEvent(String stringMsg)
        throws ServiceException, NBEventException {
        if (stringMsg.equals("")) {
            stringMsg += System.currentTimeMillis();
        }

        NBEvent nbEvent = producer
            .generateEvent(TemplateProfileAndSynopsisTypes.STRING, topic,
                           stringMsg.getBytes());

        if (addEventProperty) {
            EventProperties properties = nbEvent.getEventProperties();
            properties.setMutableProperty("Athens", "Olympics",
                                          new Integer(entityId));
        }
        producer.publishEvent(nbEvent);
    }

    public void publishEvent(byte[] transferBytes)
        throws ServiceException, NBEventException {
        NBEvent nbEvent = producer
            .generateEvent(TemplateProfileAndSynopsisTypes.STRING, topic,
                           transferBytes);
        producer.publishEvent(nbEvent);
        nbEvent = null;
    }

    public void onEvent(NBEvent nbEvent) {
        String synopsis = (String) nbEvent.getContentSynopsis();
        System.out.println(moduleName + "Received NBEvent {" + synopsis + "} "
            + new String(nbEvent.getContentPayload()));
    }

    public static void main(String[] args) {
        String module = "SimpleClient.main() ->";
        int entityId = 7007;
        String transport = "niotcp";
        if (args.length < 3) {
            String errorReport = module + "The Correct arguments are \n java "
                + " cgl.narada.samples.nbNative.SimpleIPSecClient <hostname>"
                + "<portnum> <entityId> [transport: (default) niotcp]";
            System.out.println(errorReport);
            System.exit(0);
        }

        if (args.length > 2) {
            entityId = Integer.parseInt(args[2]);
        }

        if (args.length > 3) {
            transport = args[3];
        }

        System.out.println(module + "Specified entity id is " + entityId);
        SimpleIPSecClient client = new SimpleIPSecClient(entityId);
        Properties props = new Properties();

        /** These properties pertain to setting up a TCP link */
        props.put("hostname", args[0]);
        props.put("portnum", args[1]);

        props.put("IPSecHostname", args[0]);
        props.put("IPSecSharedSecret", "s3cr3t");

        /**
         * You can override the default values that would be assigned to the
         * policy ("NaradaBrokering_Policy) and rule ("NaradaBrokering_Rule")
         */
        props.put("IPSecPolicyName", "NB_Policy");
        props.put("IPSecRuleName", "NB_Rule");

        String helpInfo = "SimpleClient is meant to demonstrate some basic capabilities"
            + "\nThe various options currently available include\n"
            + "ANY TEXT : If you start typing followed by a carriage return, message is sent\n"
            + "u        : Perform an unsubscribe operation.\n"
            + "i        : Initialize consumer.\n"
            + "h        : Displays HELP options\n"
            + "q        : Close broker connections and quit the system";
        try {

            client.initializeBrokerCommunications(props, "ipsec");

            /** Initializing communications using specified transport */
            client.initializeBrokerCommunications(props, transport);
            client.initializeProducer();
            client.initializeConsumer();

            BufferedReader commandLine = new BufferedReader(
                                                            new InputStreamReader(
                                                                                  System.in));
            System.out.println(helpInfo);
            int tracker = 0;
            while (true) {
                String s = commandLine.readLine();
                if (s == null) {
                    System.out.println(module + "String is null!!!");
                    break;
                }

                if (s.equals("h")) {
                    System.out.println(helpInfo);
                }

                if (s.equals("q")) {
                    client.closeBrokerConnection();
                    System.out.print(module + "Closed Broker Connection");
                    break;
                }

                if (s.equals("u")) {
                    client.unsubscribe();
                }

                if (s.equals("s")) {
                    client.initializeConsumer();
                }

                tracker++;
                client.publishEvent(s + " [" + tracker + "]");

            }
            /** end while-true */
            System.out.println(module + "exiting ");

        } catch (IOException ioe) {
            System.out.println(ioe);
        } catch (ServiceException serEx) {
            System.out.println(serEx);
        } catch (NBEventException nbe) {
            System.out.println(nbe);
        }

        ThreadGroup tg = Thread.currentThread().getThreadGroup();
        int activeCount = tg.activeCount();
        if (activeCount != 0) {
            Thread[] threads = new Thread[activeCount];
            tg.enumerate(threads);

            for (int i = 0; i < activeCount; i++) {
                System.out.println(threads[i].getName());
            }/* end for */

        }/* end if */

    }
}
